<?php
namespace Model\System;
use Core\Model;
use Libs\Fun;

/**
 * 生成唯一编码
 * Class UniqueCode
 */

class UniqueCode extends Model
{
    //获取今天从1开始递增的值
    public static function getGlobalId($len = 6)
    {
        $today = date('Ymd');
        //1. 插入一条记录
        $id = self::link('gid')
            ->insert(['create_day' => $today])
            ->insertId;

        //2. 取出今天最小ID
        $min = self::link('gid')
            ->fields('id')
            ->where(['create_day' => $today])
            ->order('id asc')
            ->limit(1)
            ->select()
            ->getOne();

        //2. 相减计算得到差值
        $offset = bcadd(bcsub($id, $min['id']), 1);

        return $today.str_pad($offset, $len, '0', STR_PAD_LEFT);
    }

    //用户唯一编码
    public static function getUserCode()
    {
        $code = self::getGlobalId();
        $char = Fun::randChar(2); //随机码
        return 'U'.$code.$char;
    }

    //消息唯一编码
    public static function getMessageCode()
    {
        $code = self::getGlobalId();
        $char = Fun::randChar(2); //随机码
        return 'MQ'.$code.$char;
    }

}